<?php namespace App\Models\Cxhshop;

use App\Models\Base\CxhshopBase;
use App\Models\Cxhshop\Dispatch;
use App\Models\Cxhshop\Income;

use Illuminate\Support\Facades\DB;
use App\Models\Cxhshop\ShopMember;


class Order extends CxhshopBase { 

    public $timestamps = false;//这里表示的是不添加时间
    protected $table = 'ims_ewei_shop_order'; 
    public  $arr = array();
       /**
     * 下单数据
     * @var array
     * array() goods 商品信息  
     * 
     * array() updategoods 要更新的商品信息
     * order 要更新的订单数据 
     * ordergoods 要更新的订单商品信息 
     * updateoption 规格sha更新
     * 二维数组  singlegoods 列子 array(2=>('num'=>3,'price'=>32),'5'=>('discountprice'=>43))
     * corelog  下订单日志 以后支付的时候会用到表
     * array() newtotalgoods 更改过后的商品部分信息 (订单总属性  以后会用到) 
     */
    private $_order_data = array();

    
    public function  _createOrderStep1($param){ 
        $arr['res'] = 1;
        //是否支持货到付款
        //验证收货地址
        if(empty($param['addressid']) || $param['addressid']<0){
            $arr['res'] = 0;
            $arr['msg'] = '缺少收货地址id';
            return $arr;
        }
        $addres = DB::connection('jmft_cxh')->table('ims_ewei_shop_member_address')->where('id',$param['addressid'])->first();
        if(empty($addres)){
            $arr['res'] = 0;
            $arr['msg'] = '没有找到收货地址信息';
            return $arr;
        }
        
        $this->_order_data['order']['address'] = serialize($addres);
        
        $this->_order_data['order']['addressid'] = $param['addressid'];

        $data = DB::connection('jmft_cxh')->table('ims_ewei_shop_goods')->where('id',$param['goods']['0']['goodsid'])->get();
        if(empty($data)){
            $arr['res'] = 0;
            $arr['msg'] = '没有找到该商品信息';
            return $arr;
           
        }
        $data = json_decode($data,true);
        $goods = $data['0'];
        
        //先计算单个 
        $this->_order_data['goods'] = $goods;
      
        //查询是否是多规格商品(选中的其中一个)
        if(!empty($param['goods']['0']['optionid'])){
            $option = DB::connection('jmft_cxh')->table('ims_ewei_shop_goods_option')->where('id',$param['goods']['0']['optionid'])->get();
            if(empty($option)){
                $arr['res'] = 0;
                $arr['msg'] = '没有找到该商品规格';
                return $arr;
            }
            $option = json_decode($option,true);
            $this->_order_data['goods']['ifoption'] = 1;
            $this->_order_data['goods']['option'] = $option['0'];

        }else{
            $this->_order_data['goods']['ifoption'] = 0;
        }

        //判断计算运费情况 
        //免邮
        if($goods['issendfree']==1){
            $this->_order_data['order']['dispatchprice'] =0;
        }else{
            //固定邮费
            if($goods['dispatchtype']==1){
                $this->_order_data['order']['dispatchprice'] = $goods['dispatchprice'];
                $this->_order_data['order']['dispatchtype'] = 1;
            }else{
                $model = new Dispatch;
                //默认
                if($goods['dispatchid']==0){
                    $dispatch = $model->getDefaultDispatch();
                    if(empty($dispatch)){
                        $arr['res'] = 0;
                        $arr['msg'] = '请开启默认配送模板';
                        return $arr;
                    } 
                }else{
                    $dispatch = $model->getOneDispatch($goods['dispatchid']);
                    if(empty($dispatch)){
                        $arr['res'] = 0;
                        $arr['msg'] = '未找到对应的运费模板';
                        return $arr;
                    } 
                }
                //判断配送区域  
                $dispatch =  $dispatch->toArray(); 
                $dispatch_array = unserialize($dispatch['nodispatchareas']);
                $dispatch_array = explode(';',$dispatch_array);
               
                //固定配送地区 和不配送地区 
                if($dispatch['isdispatcharea']==1){
                    //只配送地区
                    if(!in_array($addres->city,$dispatch_array)){
                        $arr['res'] = 0;
                        $arr['msg'] = '不支持配送到'.$addres->city;
                        return $arr;
                    }
                }else{
                    //不配送地区
                    if(in_array($addres->city,$dispatch_array)){
                        $arr['res'] = 0;
                        $arr['msg'] = '不支持配送到'.$addres->city;
                        return $arr;
                    }
                }
                //可以判断件数
                // 判断邮费信息等等  按体积 
                if($dispatch['calculatetype'] == 1){
                    //开始计算
                    $num = $param['goods']['0']['num'];
                    $dispatchprice = $model->getDispatchPrice($num,$dispatch);
                //按重量
                }else{
                    $weight = ($goods['weight'])*$param['goods']['0']['num'];
                    $dispatchprice = $model->getDispatchPrice($weight,$dispatch);
                }
                $this->_order_data['order']['dispatchprice'] = $dispatchprice;
                $this->_order_data['order']['dispatchid'] = $dispatch['id'];
                //判断是否有 陪护的快递 
                if($dispatch['express']){
                    $express = DB::connection('jmft_cxh')->table('ims_ewei_shop_express')->where('express',$dispatch['express'])->first();
                    $this->_order_data['order']['express'] = $express->express;
                    $this->_order_data['order']['expresscom'] = $express->name;
                    $this->_order_data['order']['expresssn'] = date('Y-m-d');
                }
            }
        }
        return $arr;
        
    }
    //变更库存和销量
    public function  _createOrderStep2($param){
        $arr['res'] = 1;
        //先判断库存
        if($this->_order_data['goods']['ifoption']==0){
            if($this->_order_data['goods']['total']<$param['goods']['0']['num']){
                $arr['res'] = 0;
                $arr['msg'] = '库存不足';
                return $arr;
            }
        }else{
            if($this->_order_data['goods']['option']['stock']<$param['goods']['0']['num']){
                $arr['res'] = 0;
                $arr['msg'] = '库存不足';
                return $arr;
            }
        }
        
        //单次最多购买
        $maxbuy = $this->_order_data['goods']['maxbuy'];
        if($maxbuy>0 && $maxbuy<$param['goods']['0']['num']){
            $arr['res'] = 0;
            $arr['msg'] = '单次购买超过商品最多购买数';
            return $arr;
        }
        //单次最少购买
        $minbuy = $this->_order_data['goods']['minbuy'];
        if($minbuy>0 && $minbuy>$param['goods']['0']['num']){
            $arr['res'] = 0;
            $arr['msg'] = '单次购买低于商品最少购买数';
            return $arr;
        }
        $usermaxbuy = $this->_order_data['goods']['usermaxbuy'];
        if($usermaxbuy>0 && $usermaxbuy<$param['goods']['0']['num']){
            $arr['res'] = 0;
            $arr['msg'] = '超过该商品最多购买数';
            return $arr;
        }
        // 0  拍下减库存  1  付款减库存  2 永不减库存  
        if($this->_order_data['goods']['totalcnf']==0){
            if($this->_order_data['goods']['ifoption']==1){
                $this->_order_data['updateoption']['stock'] = $this->_order_data['goods']['option']['stock'] -$param['goods']['0']['num']; 
            }
            $this->_order_data['updategoods']['total'] =$this->_order_data['goods']['total'] -$param['goods']['0']['num'];
        }
        // 增加销量 
        $this->_order_data['updategoods']['sales'] =$this->_order_data['goods']['sales'] +$param['goods']['0']['num'];
        return $arr;
    } 
    //购物车 和直接购买的 处理 
    public function  _createOrderStep3($param){
        $arr['res'] = 1;
        
        //判断是否是升级会员的订单 
        if($this->_order_data['goods']['cates'] == '1190' || $this->_order_data['goods']['cates'] == '1189' || $this->_order_data['goods']['cates'] == '1191') {
			$this->_order_data['order']['isupgrade'] = 1;
        }
        return $arr;
        //纯金额 
        //纯积分
        //混合支付 
       
    } 
    // public function  _createOrderStep4(){
    //     //满减
    //     //相关活动


    // }

    
    //生成订单
    public function  _createOrderStep5($param){
        $arr['res'] = 1;
        $time = time();
        $membermodel = new ShopMember();
        $fields = ['openid'];
        $nums = $param['goods']['0']['num'];
        $memInfo = $membermodel->getMemInfo($param['uid'],$fields);
        $openid = $memInfo['openid'];
        $ordersn = $this->createNO('order','ordersn','SH');
        //生成订单号 
        $this->_order_data['order']['ordersn'] =$ordersn;
        $this->_order_data['order']['uniacid'] =1;
        $this->_order_data['order']['openid'] =$openid;
        $this->_order_data['order']['createtime'] = $time;
      
        //总价(无活动的时候)//商品 价格  包括数目
        $this->_order_data['order']['price'] =$nums*$this->_order_data['goods']['marketprice'];
        $this->_order_data['order']['goodsprice'] = $nums*$this->_order_data['goods']['marketprice'];
        $this->_order_data['order']['oldprice'] =$nums*$this->_order_data['goods']['marketprice'];

        //当有规格的时候
        if($this->_order_data['goods']['ifoption']>0){
            $this->_order_data['order']['price'] = $nums*$this->_order_data['goods']['option']['marketprice'];
            $this->_order_data['order']['goodsprice'] = $nums*$this->_order_data['goods']['option']['marketprice'];
            $this->_order_data['order']['oldprice'] =$nums*$this->_order_data['goods']['option']['marketprice'];
        }
        //有邮费的时候
        if($this->_order_data['order']['dispatchprice']>0){
            $this->_order_data['order']['price'] += $this->_order_data['order']['dispatchprice'];
        }
        
        //当为混合支付的时候 改变point   //规格里面有积分 
        if($this->_order_data['goods']['can_mix']>0){
            $this->_order_data['order']['can_mix'] = 1;
            $this->_order_data['order']['point'] = $this->_order_data['goods']['point'];
            if($this->_order_data['goods']['ifoption']>0 &&  $this->_order_data['goods']['option']['point']>0){
                $this->_order_data['order']['point'] = $this->_order_data['goods']['option']['point'];
            }
        }

        //邮费到付的情况
        if($this->_order_data['goods']['pay_postage']>0){
            $this->_order_data['order']['dispatchprice']= 0;
            $this->_order_data['order']['dispatchid']= 0; 
        }

        //支付方式  生成订单的时候不管

        //订单商品
        $this->_order_data['ordergoods']['remarksend'] ='';
        $this->_order_data['ordergoods']['uniacid'] = 1;
        $this->_order_data['ordergoods']['createtime'] = $time;
        //成本单价
        $this->_order_data['ordergoods']['costprice'] = $this->_order_data['goods']['costprice'];
        $this->_order_data['ordergoods']['goodsid'] = $this->_order_data['goods']['id'];
        $this->_order_data['ordergoods']['openid'] = $openid;
        $this->_order_data['ordergoods']['price'] = $this->_order_data['order']['price'];
        $this->_order_data['ordergoods']['total'] = $nums;
        $this->_order_data['ordergoods']['realprice'] = $this->_order_data['order']['price'];
        $this->_order_data['ordergoods']['oldprice'] = $this->_order_data['order']['price'];
        if($this->_order_data['goods']['ifoption']>0){
            $this->_order_data['ordergoods']['optionid'] = $this->_order_data['goods']['option']['id'];
            $this->_order_data['ordergoods']['optionname'] = $this->_order_data['goods']['option']['title'];
        }
        if(!empty($this->_order_data['order']['point'])){
            $this->_order_data['ordergoods']['point'] = $this->_order_data['order']['point'];
        }

        //core 的 生成  
        $this->_order_data['corelog']['uniacid'] =1;
        $this->_order_data['corelog']['openid'] =$openid;
        $this->_order_data['corelog']['tid'] =$ordersn;
        $this->_order_data['corelog']['module'] = 'cxh_app';
        $this->_order_data['corelog']['is_usecard'] = 0;
        $this->_order_data['corelog']['card_type'] = 0;
        $this->_order_data['corelog']['card_id'] = 0;
        $this->_order_data['corelog']['card_fee'] = 0;
        $this->_order_data['corelog']['acid'] = 0;
        $this->_order_data['corelog']['fee'] =$this->_order_data['order']['price'];
        //事务操作
        DB::connection('jmft_cxh')->beginTransaction();
        $orderid  = DB::connection('jmft_cxh')->table('ims_ewei_shop_order')->insertGetId($this->_order_data['order']);
        if($orderid){
            //库存 销量判断
            if(!empty($this->_order_data['updategoods'])){
                $goodsid = $this->_order_data['goods']['id'];
                $res[] = DB::connection('jmft_cxh')->table('ims_ewei_shop_goods')->where('id','=',$goodsid)->update($this->_order_data['updategoods']);
            }
            // 多规格 减库存

            if(!empty($this->_order_data['updateoption'])){
                $optionid = $this->_order_data['goods']['option']['id'];
                $res[] = DB::connection('jmft_cxh')->table('ims_ewei_shop_goods_option')->where('id','=',$optionid)->update($this->_order_data['updateoption']);
            }
            $this->_order_data['ordergoods']['orderid'] = $orderid;
            $res[]= DB::connection('jmft_cxh')->table('ims_ewei_shop_order_goods')->insert($this->_order_data['ordergoods']);
            $res[]= DB::connection('jmft_cxh')->table('ims_core_paylog')->insert($this->_order_data['corelog']);

            if(in_array('',$res) || in_array(0, $res) || in_array(false, $res)){
                DB::connection('jmft_cxh')->rollBack();
                $arr['res'] = 0;
                $arr['msg'] = '生成订单失败';
            }else{
                DB::connection('jmft_cxh')->commit();
            }
            return $arr;
           
        }else{
            $arr['res'] = 0;
            $arr['msg'] = '生成订单失败';
            return $arr;
        }
    }
    // public function  _createOrderStep6(){
    //     预存款

    // }
   
    
 
 
    //订单列表页面
    public function orderList($condition,$page=1,$number =10){  
        $field = ['ordersn','id','status','price','createtime','can_mix','point','refundid','ac_point'];
        $goodsfield = ['a.title','a.thumb','b.total','b.price as goodsprice','a.cannotrefund as if_refund','a.can_mix','a.point'];
        $refundid = ['status','rtype'];
        $query = self::query();
       
        if($condition['status'] && $condition['status'] == 22){
            $query = $query->where('deleted','=',0)-> where('openid','=',$condition['openid']) -> where('refundid','>',0);
        }elseif($condition['status']){
            $query = $query->where('deleted','=',0)-> where('openid', '=', $condition['openid'])-> where('status', '=', $condition['status']);
        }else{
            $query = $query->where('deleted','=',0)-> where('openid', '=', $condition['openid']);
        }
//        if(isset($condition['status'])){
//            $query = $query->where('deleted','=',0)-> where('openid', '=', $condition['openid'])-> where('status', '=', $condition['status']);
//        }else{
//            $query = $query->where('deleted','=',0)-> where('openid', '=', $condition['openid']);
//        }

        $query = $query->forPage($page,$number)->get($field);
        $count = $query->count();
        if($count>0){
            $data = $query-> toArray(); 
            foreach($data as $key => &$v){
                $data[$key]['goods'] =DB::connection('jmft_cxh')->table('ims_ewei_shop_order_goods as b')
                ->join('ims_ewei_shop_goods as a', 'a.id', '=', 'b.goodsid')
                ->where('b.orderid','=',$v['id'])->get($goodsfield);
                $data[$key]['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
                if($v['refundid']>0){
                    $data[$key]['refund'] =DB::connection('jmft_cxh')->table('ims_ewei_shop_order_refund')->where('id','=',$v['refundid'])->first($refundid);
                }
            }
            if($condition['status'] == 22){//退换货的话，还要判断一下退款拒绝的订单，剔除
                foreach ($data as $key=>$val){
                    $rFundInfo = (array)$val['refund'];
                    if($rFundInfo['status'] == -1){
                        unset($data[$key]);
                        $data = array_values($data);
                    }
                }
            }
            return $data;
        }else{
            return false;
        }
    }
    //订单详情页面
    public function orderDetail($ordersn){   
        $query = self::query();
        $field = ['ordersn','price','sendtime','goodsprice as totalgoodsprice','status','dispatchprice','createtime','paytime','refundid','id','addressid','can_mix','point','ac_point'];
        $goodsfield = ['a.title','a.thumb','b.total','b.price as goodsprice','a.cannotrefund as if_refund','a.can_mix','a.point'];
        $addressfield = ['realname','mobile','province','city','area','address'];
        $refundid = ['status','rtype'];
        $query = $query ->where('ordersn','=',$ordersn)->first($field);
        $count =  $query->count();
        if($count>0){
            $data = $query->toArray();
           
            $data['createtime'] = date('Y-m-d H:i:s',$data['createtime']);
            if($data['paytime']){
                $data['paytime'] = date('Y-m-d H:i:s',$data['paytime']);
            }
            if($data['sendtime']){
                $data['sendtime'] = date('Y-m-d H:i:s',$data['sendtime']);
            }

            $data['goods'] =DB::connection('jmft_cxh')->table('ims_ewei_shop_order_goods as b')
                ->join('ims_ewei_shop_goods as a', 'a.id', '=', 'b.goodsid')
            ->where('b.orderid','=',$data['id'])->get($goodsfield);
            $data['address'] = DB::connection('jmft_cxh')->table('ims_ewei_shop_member_address')
                ->where('id','=',$data['addressid'])->first($addressfield);
            if(!empty($v['address'])){
                $data['address'] =  $data['address']->toArray();
            }
            if($data['refundid']>0){
                $data['refund'] =DB::connection('jmft_cxh')->table('ims_ewei_shop_order_refund')->where('id','=',$data['refundid'])->first($refundid);
            }
            return $data;
        }else{
            return false;
        }
      
    }
 
    //确认订单 
    public function finishorder($param){   
        $res['res'] =1;
        $field = ['*'];
        $query = self::query();
        $data =$query->where('ordersn',$param['ordersn'])->first();
        if(!empty($data)){
            $data = json_decode($data,true);
            //提成判断(只有金额那块有提成)
            if($data['paytype']==20 || $data['paytype']==30){
            }else{
                $incomemodel = new Income();
                //礼包 有自己的提成
                if($data['isupgrade']==1){
                    $incomemodel->membership_gift_bag($param['member_id'],$data['price']);
                }else{
                //金额提成 
                    $incomemodel->goods_sale($param['member_id'],$data['id']);
                }
            }
            
            //订单状态更新 
            $result = $query->where('ordersn','=',$param['ordersn'])->update(['status'=>3]);
            if($result){
                return $res;
            }else{
                $res['res'] =0;
                $res['msg'] ='订单更新失败';
                return $res;
            }
            
        }else{
            $res['res'] =0;
            $res['msg'] ='未获取到订单信息';
            return $res;
        }

    }
    //取消订单
    public function cancelorder($ordersn)
    {
        $res = self::where('ordersn',$ordersn)->update(['status'=>-1]);
        return $res;
    }
    //删除订单
    public function delorder($ordersn)
    {
          $res = self::where('ordersn',$ordersn)->update(['deleted'=>1]);
          return $res;
    }

    /**
     * @param $openid
     * @return array
     * 获取退款订单信息
     */
    public function refundOrder($openid){
        //获取该用户多有的订单，并且有退款id的记录
        $orderInfo = [];
        $query = self::query();
        $list = $query -> where('openid',$openid) -> where('refundid','>',0) -> get(['id','openid','price','goodsprice','refundid','createtime']);
        if($list){
           $data = $list -> toArray();
           foreach ($data as $key=>$val){
               $orderInfo[$key]['price'] = $val['price'];
               $orderGoods = DB::connection('jmft_cxh')
                   -> table("ims_ewei_shop_order_goods")
                   -> where('orderid',$val['id'])
                   -> first(['goodsid','total']);
               if($orderGoods){
                  $goods = (array)$orderGoods;
                  $goodsInfo = DB::connection('jmft_cxh')
                      -> table("ims_ewei_shop_goods")
                      -> where('id',$goods['goodsid'])
                      -> first(['title','thumb']);
                   $goodsInfo = (array)$goodsInfo;
                   $orderInfo[$key]['num'] = $goods['total'];
                   $orderInfo[$key]['title'] = $goodsInfo['title'];
                   $orderInfo[$key]['thumb'] = $goodsInfo['thumb'];
               }else{
                   $orderInfo[$key]['title'] = '';
                   $orderInfo[$key]['thumb'] = '';
                   $orderInfo[$key]['num'] = '';
               }
               //获取退换货状态
               $refundStatus = DB::connection('jmft_cxh')
                   -> table("ims_ewei_shop_order_refund")
                   -> where('id',$val['refundid'])
                   -> first(['status']);
               $refundStatus = (array)$refundStatus;
               $orderInfo[$key]['status'] = $refundStatus['status'];
               $orderInfo[$key]['ctime'] = date("Y-m-d H:i:s",$val['createtime']);
           }
        }
        return $orderInfo;
    }

    /**
     * 支付页数据
     * @param string $no 订单号
     * @param string $uid 用户uuid
     * @return array
     */
    public function payDetail($no, $uid) {

        $query = self::query();
        $order = $query -> where('ordersn', $no) -> first(['id', 'ordersn', 'price', 'status', 'can_mix', 'point']);
        
        // if(!$order || $order->status!=0) {
        //     return null;
        // }
        $order = $order->toArray();
        $credit3 = true;  //初始化预付积分
        $credit1 = true;  //初始化购物积分
        $order_goods = DB::connection('jmft_cxh') -> table('ims_ewei_shop_order_goods') -> where('orderid', $order['id']) -> get();
        foreach($order_goods as $key => $value) {
            $good = DB::connection('jmft_cxh') -> table('ims_ewei_shop_goods') -> where('id', $value->goodsid) -> first(['can_credit1', 'can_credit3']);
            if(!$good->can_credit1) {
                $credit1 = false;
            }
            if(!$good->can_credit3) {
                $credit3 = false;
            }
        }

        $order['credit1'] = $credit1;
        $order['credit3'] = $credit3;
        
        $membermodel = new ShopMember();
        $member = $membermodel -> getMemInfo($uid, ['credit1', 'credit2', 'credit3']);
        $order['member_credit1'] = $member['credit1'];
        $order['member_credit2'] = $member['credit2'];
        $order['member_credit3'] = $member['credit3'];

        return $order;

    }

    
}